//
//  weeklyReport.swift
//  HanMeiMei
//
//  Created by xiaoyu on 2019/1/24.
//

import Foundation

func weeklyReportJudge(day: String, hour: Int, minute: Int) -> Void {
    let weekDays = ["","周日","周一","周二","周三","周四","周五","周六"]
    let calendar = Calendar.init(identifier: .gregorian)
    
    let dateFormater = DateFormatter.init()
    dateFormater.dateFormat = "yyyyMMdd"
    let date = dateFormater.date(from: day)
    let theIndex = calendar.component(.weekday, from: date ?? Date())
    let dateString = weekDays[theIndex]
    
    if dateString == "周四" {
        if (hour == 17 && minute >= 30) {
            weeklyReportNotifyRequest(day: day)
        }
    } else if dateString == "周五" {
        if (hour == 11 && minute >= 30) {
            weeklyReportNotifyRequest(day: day)
        }
    }
}

var globalWeekReportNotifyDictionary : Dictionary<String, Bool> = Dictionary.init()
private let weekReportSession: URLSession = URLSession.init(configuration: .default)

private func weeklyReportNotifyRequest(day: String) -> Void {
    let finalNotifySaveKey = day
    if (globalWeekReportNotifyDictionary[finalNotifySaveKey] ?? false == false) {
        globalWeekReportNotifyDictionary[finalNotifySaveKey] = true
        
        let url = "https://oapi.dingtalk.com/robot/send?access_token=6061ab732a4e0b7f9b86e198a164241195b08c247d5f204f9da32232e17de38f"
        
        var req = URLRequest.init(url: (URL.init(string: url) ?? nil)!)
        req.httpMethod = "POST"
        req.addValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
        
        let noti_content = "@所有人 （敲黑板）Miss Gao 提醒：周报周报周报！！！"
        
        let textnoti = "{\"msgtype\": \"text\",\"text\": {\"content\": \"\(noti_content)\"},\"at\":{\"atMobiles\": [],\"isAtAll\": true}}"
        req.httpBody = textnoti.data(using: String.Encoding.utf8)
        
        let textTask = weekReportSession.dataTask(with: req, completionHandler: { (data, resp, error) in
            if (error != nil) {
                print("Notify Request Return Error : \(error!)")
            }
        })
        textTask.resume()
        
    } else {
        //                print("Judge Notify -> forbben")
    }
}
